package com.kyle.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kyle.dao.DeptDao;
import com.kyle.dao.UserDao;
import com.kyle.entity.DeptEntity;
import com.kyle.entity.Menu;
import com.kyle.entity.util.JsonResult;
import com.kyle.entity.util.PageBean;

@Controller
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/dept")
public class DeptAction {

	@Autowired
	@Qualifier(value="deptDao")
	private DeptDao deptDao;
	
	@RequestMapping(value="/getAllDept.xhtml")
	@ResponseBody
	public Object getAllDept(HttpServletRequest request,HttpServletResponse response){
		List<DeptEntity> deptList = deptDao.getAllEntry();
		return deptList;
	}
	
	@RequestMapping(value="/getDeptListByPId.xhtml")
	@ResponseBody
	public JsonResult getDeptListByPId(PageBean pageBean,Integer pid,String name,
			HttpServletRequest request,HttpServletResponse response){
		JsonResult jsonResult = new JsonResult();
		
		StringBuilder queryFromSb = new StringBuilder();
		queryFromSb.append("o.pid=?");
		
		List<Object> params = new ArrayList<Object>();
		params.add(pid);//选择条件
		
		//前台查找条件
		if(name!=null){
			queryFromSb.append(" and o.name like ? ");
			params.add("%"+name+"%");
		}
		List<DeptEntity> deList = deptDao.getScrollData(pageBean, queryFromSb.toString(), params.toArray(), null);
		Object rows = deptDao.getScrollDataCount(queryFromSb.toString(), params.toArray());
		jsonResult.setTotal(rows);
		jsonResult.setRows(deList);
		return jsonResult;
	}
	
	@RequestMapping(value="/addDept.xhtml")
	@ResponseBody
	public JsonResult addDept(DeptEntity dept,HttpServletRequest request,HttpServletResponse response){
		JsonResult jsonResult = new JsonResult();
		try {
			deptDao.saveEntity(dept);
			jsonResult.setMsg("添加成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jsonResult.setState(false);
			jsonResult.setMsg("添加失败");
		}	
		return jsonResult;
	}
}
